package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoaiteacher.Constant;
import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.adapter.StoryNumberListAdapter;
import com.jdy.haoduoaiteacher.adapter.StoryNumberListAdapter.OnMenuClickListener;
import com.jdy.haoduoaiteacher.enums.MediaType;
import com.jdy.haoduoaiteacher.enums.PlayState;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.intface.IMParseListener;
import com.jdy.haoduoaiteacher.model.AlbumCollectionItem;
import com.jdy.haoduoaiteacher.model.AlbumItem;
import com.jdy.haoduoaiteacher.model.CartoonVo;
import com.jdy.haoduoaiteacher.model.LeMachine;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.PlaylistItem;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoaiteacher.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoaiteacher.util.BlurTransformation;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.DateUtils;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ImageLoader;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.OnDataReceivedListener;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.RoundedTransformation;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.swipemenu.SwipeMenu;
import com.jdy.haoduoaiteacher.view.swipemenu.SwipeMenuCreator;
import com.jdy.haoduoaiteacher.view.swipemenu.SwipeMenuItem;
import com.jdy.haoduoaiteacher.view.swipemenu.SwipeMenuListView;
import com.jdy.haoduoaiteacher.view.visualizer.FrequencyDistributionBarView;
import com.jdy.haoduoaiteacher.widget.CustomDetailDialog;
import com.jdy.haoduoaiteacher.widget.CustomMarkingDialog;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoaiteacher.R;

//import com.jdy.haoduoaiteacher.util.ImHelper;
//import com.tencent.TIMConnListener;
//import com.tencent.TIMManager;
//import com.jdy.haoduoaiteacher.widget.VerticalSeekBar;
//import com.jdy.haoduoaiteacher.widget.VerticalSeekBar.OnSeekBarChangeListener;

@SuppressLint("ClickableViewAccessibility")
public class StoryDetailActivity extends BaseActivity implements
        OnClickListener, /* OnSeekBarChangeListener, */OnItemClickListener,
        OnMenuClickListener, IMParseListener, /* DownloadStateListener, */
        OnDataReceivedListener {

    @InjectView(id = R.id.tab2)
    private RadioButton mTab2;
    @InjectView(id = R.id.name)
    private TextView title;
    @InjectView(id = R.id.backs, click = true)
    private View back;
    @InjectView(id = R.id.img_cover)
    private ImageView img_cover;
    @InjectView(id = R.id.marking_img, click = true)
    private ImageView mMarkingImg;
    @InjectView(id = R.id.conver_blur_layout)
    private RelativeLayout mCoverBlurLayout;
    @InjectView(id = R.id.mydevice_layout, click = true)
    private RelativeLayout mDeviceLayout;
    @InjectView(id = R.id.storylist_pulltorefreshlayout)
    private PullToRefreshLayout storylistPullLayout;
    @InjectView(id = R.id.storylist)
    private SwipeMenuListView storylist;
    @InjectView(id = R.id.device_stateview, click = true)
    private FrequencyDistributionBarView device_stateview;

    // int sumcount, playid;
    private String coverUrl;
    // boolean isPlay = false;
    public CompoundButton currentButtonView;
    // private int mCurrentPlayMode;
    private CustomDetailDialog mCustomDetailDialog;
    private AlbumCollectionItem detailVo;
    private LeUser leUser;
    private String content;
    private int sumhit;
    private String ctime;
    private String ageRange;
    private int album_id;
    private String catalog;

    private ImageLoader mImageLoader;
    private CustomMarkingDialog mMarkingDialog;

    public int curPos = -2;

    private StoryNumberListAdapter mNumberAdapter;
    private int mLastpage = 1;
    public boolean isrefreshlist = false;
    private int mSort = -1;
    ;
    private ArrayList<AlbumItem> mAdapterList = null;
    private ArrayList<AlbumItem> mArrayList = null;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.storydetail_layout);
        hideTitleView();

        bindService();
        initialize();
        initListener();
        requestData();
        getEpisode(false);

        storylistPullLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                mLastpage = 1;
                isrefreshlist = true;
                getEpisode(false);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                mLastpage++;
                isrefreshlist = false;
                getEpisode(true);
            }
        });

//        TIMManager.getInstance().setConnectionListener(new TIMConnListener() {
//
//            @Override
//            public void onWifiNeedAuth(String arg0) {
//                // TODO Auto-generated method stub
//
//            }
//
//            @Override
//            public void onDisconnected(int arg0, String arg1) {
//                LeConfig.isDeviceConnect = false;
//
//                if (device_stateview != null) {
//                    device_stateview.setPlaying(false);
//                }
//            }
//
//            @Override
//            public void onConnected() {
//                // TODO Auto-generated method stub
//
//            }
//        });

    }

//    private ImHelper mImHelper;

    private void bindService() {

//        mImHelper = MyTeacherApp.getInstance().getImHelper();
//        if (mImHelper != null && mImHelper.isLogin()) {
//            mImHelper.setOnDataReceivedListener(this);
//            mImHelper.setIMParseListener(this);
//
//            try {
//                JSONObject dataJson = new JSONObject();
//                dataJson.put("code", "app");
//                dataJson.put("act", "machineinfo");
//                mImHelper.send(dataJson.toString());
//            } catch (JSONException e) {
//                e.printStackTrace();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }

    /**
     * 专辑下的小集
     *
     * @param isLoadMore 是否为上拉加载更多
     */
    private void getEpisode(final boolean isLoadMore) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    try {
                        JSONObject json = new JSONObject(result.data);
                        String data = json.optString("data");
                        JSONArray array = new JSONArray(data);
                        if (mAdapterList != null) {
                            mAdapterList.clear();
                        }
                        if (isrefreshlist) {
                            mArrayList.clear();
                        }
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject obj = ((JSONObject) array.opt(i));

                            if (Tools.isNotEmpty(obj.toString())) {
                                AlbumItem itemVo = JsonSerializer.getInstance().deserialize(
                                        obj.toString(), AlbumItem.class);
                                mAdapterList.add(itemVo);
                            }

                        }
                    } catch (Exception e) {
                    }
                    mArrayList.addAll(mAdapterList);
                    setView(isLoadMore);
                } else {
                    if (Tools.isNotNullStr(result.data)) {
                        Toast.makeText(StoryDetailActivity.this, result.data,
                                Toast.LENGTH_SHORT).show();
                    }

                    storylistPullLayout.refreshFinish(PullToRefreshLayout.FAIL);
                    storylistPullLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {

                if (leUser == null) {
                    leUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                if (mCartoonVo != null) {
                    param_.put("album_id", mCartoonVo.id);
                } else {
                    param_.put("album_id", album_id);
                }

                param_.put("page", mLastpage);
                return HttpUtils.startRequest(HttpUtils.HOST_API
                        + HttpUtils.GET_EPISODE_LIST, param_, HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        AlbumItem episodeVo = mArrayList.get(position);
        mNumberAdapter.setSelectedRotatePosition(-1);
        mNumberAdapter.setHighLightPosition(position);
        int sid = episodeVo.id;

        onStoryListClicked(sid);
    }

    @SuppressLint("SimpleDateFormat")
    private String getDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(new java.util.Date());
    }

    private boolean isExists(List<PlaylistItem> list, PlaylistItem other) {

        if (Tools.isNotEmpty(list)) {
            for (PlaylistItem item : list) {
                if (item.EpisodeId == other.EpisodeId) {
                    return true;
                } else {
                    return false;
                }
            }
        }

        return false;
    }

    @SuppressWarnings("unchecked")
    private void addToPlayList(int id, String name, String album_name,
                               String subtitle, String reslen, String order) {

        PlaylistItem item = new PlaylistItem();
        item.EpisodeId = id;
        item.AddedTime = getDate();
        item.SubTitle = name;
        item.Order = Integer.parseInt(order);
        item.TimeRange = reslen;
        item.CollectionTitle = album_name;

        SharedPreferences prefs = getSharedPreferences(Constant.PLAYLIST,
                Context.MODE_PRIVATE);

        String result = prefs.getString(getDate(), "");

        List<PlaylistItem> newList = new ArrayList<PlaylistItem>();
        newList.add(item);
        if (Tools.isNotEmpty(result)) {
            List<PlaylistItem> playlist = (List<PlaylistItem>) JsonSerializer
                    .getInstance().deserialize(result, ArrayList.class,
                            PlaylistItem.class);
            if (!isExists(playlist, item))
                newList.addAll(playlist);
            else {
                DateUtils.showToast(this, "已经加入过了!");
                return;
            }
        }

        String jsonString = JsonSerializer.getInstance().serialize(newList);

        prefs.edit().putString(getDate(), jsonString).apply();

        DateUtils.showToast(this, "添加成功");
    }

    private void videoOP(final int id, final int code) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result != null && result.isSuccess()) {
                    if (code == 3) {
                        // DateUtils.showToast(StoryDetailActivity.this, "收藏成功");
                    }
                }

            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                if (lu == null) {
                    lu = Tools.restoreLeUser();
                }
                if (code == 1) {

                    int uid = -1, volume = -1, minutes = -1;

                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                    param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                    param_.put(HttpUtils.TAG_ACTION_I, "download");
                    param_.put(HttpUtils.TAG_OPERATION_I, "start");
                    param_.put("mode", "im");

                    if (id != -1) {
                        param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(id));
                    }
                    if (uid != -1) {
                        param_.put(HttpUtils.TAG_UID_I, String.valueOf(uid));
                    }
                    if (volume != -1) {
                        param_.put(HttpUtils.TAG_VOLUME, String.valueOf(volume));
                    }
                    if (minutes != -1) {
                        param_.put(HttpUtils.TAG_MINUTE_I, String.valueOf(minutes));
                    }
                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                    return HttpUtils.startRequest(HttpUtils.API_URL
                                    + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
                            HttpUtils.TAG_GET_REQUEST);

                } else if (code == 3) {

                    HashMap<String, Object> param_ = new HashMap<String, Object>();

                    param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                    param_.put("category", "Album");
                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                    param_.put("foreign_id", id);

                    return HttpUtils.startRequest(HttpUtils.API_URL
                                    + HttpUtils.ADD_FAVORITE_METHOD_POST, param_,
                            HttpUtils.TAG_POST_REQUEST);

                }
                return null;
            }
        }).execute();
    }

    @Override
    public void OnClickAddToList(int id, String name, String album_name,
                                 String subtitle, String reslen, String order) {
        addToPlayList(id, name, album_name, subtitle, reslen, order);
    }

    @Override
    public void OnClickStoryList(int id, String name, String subtitle,
                                 String reslen, String order) {
//        startActivity(new Intent(this, MyPlaylistActivity.class));
//        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @Override
    public void OnClickDownload(int id, String name, String subtitle,
                                String reslen, String order) {
        videoOP(id, 1);
    }

    @Override
    public void OnClickFavorite(int id, String name, String subtitle,
                                String reslen, String order) {
        videoOP(id, 3);
    }

    @Override
    public void OnClickTalk(int id, String name, String subtitle, String reslen,
                            String order) {

    }

    @Override
    public void OnClickMore(final int pos, final AlbumItem ai,
                            final View loveStateImg) {
        storylist.smoothOpenMenu(pos, true);
    }

    private void initAndUpdateSwipeMenu() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu, int pos) {

                SwipeMenuItem deleteItem = new SwipeMenuItem(getApplicationContext());
                deleteItem
                        .setBackground(new ColorDrawable(Color.rgb(0xF0, 0xF0, 0xF0)));
                deleteItem.setWidth(Tools.getPixelByDip(StoryDetailActivity.this, 90));
                deleteItem.setIcon(R.drawable.download_normal);
                menu.addMenuItem(deleteItem);

                deleteItem = new SwipeMenuItem(getApplicationContext());
                deleteItem
                        .setBackground(new ColorDrawable(Color.rgb(0xF0, 0xF0, 0xF0)));
                deleteItem.setWidth(Tools.getPixelByDip(StoryDetailActivity.this, 90));

                if (mArrayList.get(pos).favorite) {
                    deleteItem.setIcon(R.drawable.love_pressed);
                } else {
                    deleteItem.setIcon(R.drawable.love_normal);
                }
                menu.addMenuItem(deleteItem);
            }
        };

        storylist.setMenuCreator(creator);
    }

    // public void sendDownloadCmd(String usrid, String machineId, AlbumItem ai,
    // String attr, String downloadact) {
    // // if (null == mSocket) {
    // // initSocket();
    // // return;
    // // }
    //
    // try {
    // JSONObject dataJson = new JSONObject();
    // dataJson.put("macid", usrid);
    // dataJson.put("op", "download");
    // dataJson.put("to", machineId);
    // dataJson.put("id", ai.id);
    // dataJson.put("url", ai.url);
    // dataJson.put("name", ai.album_name);
    // dataJson.put("title", ai.title);
    // dataJson.put("attribute", attr);
    // dataJson.put("downloadact", downloadact);
    // dataJson.put("pic", ai.album_cover);
    //
    // String getDetailsCmd = fabricateCommand(dataJson, 130);
    // Log.e("socket", getDetailsCmd);
    // TCPClient.instance().sendMsg(getDetailsCmd.toString());
    // } catch (JSONException e) {
    // e.printStackTrace();
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    // }

    private void sendDeviceDownloadMsg(String usrid, String machineId,
                                       AlbumItem ai, String downloadact) {
        if (ai != null) {

//            if (mImHelper != null && mImHelper.isLogin()) {
//                try {
//                    JSONObject dataJson = new JSONObject();
//                    dataJson.put("code", "app");
//                    dataJson.put("act", "ctldownload");
//
//                    JSONObject dataJson22 = new JSONObject();
//                    dataJson22.put("op", "download");
//                    dataJson22.put("id", ai.id);
//                    dataJson22.put("url", ai.url);
//                    dataJson22.put("name", ai.album_name);
//                    dataJson22.put("title", ai.title);
//                    dataJson22.put("attribute", catalog);
//                    dataJson22.put("downloadact", "start");
//                    dataJson22.put("pic", ai.album_cover);
//
//                    dataJson.put("data", dataJson22);
//                    mImHelper.send(dataJson.toString());
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }

            // {"code":"app","act":"ctldownload","data":{"op":"download","id":"1111","url":"","name":"","title":"","attribute":"","downloadact":"","pic":""}}

            // SocketThreadManager.getInstance().sendDownloadCmd(usrid, machineId, ai,
            // catalog, downloadact);

        }
    }

    /**
     * @param isLoadMore 是否为上拉加载更多
     */
    private void setView(boolean isLoadMore) {
        if (mNumberAdapter == null) {
            mNumberAdapter = new StoryNumberListAdapter(mArrayList, this);
            mNumberAdapter.setOnMenuClickListener(this);
            storylist.setAdapter(mNumberAdapter);

            // step 1. create a MenuCreator
            initAndUpdateSwipeMenu();

            // step 2. listener item click event
            storylist
                    .setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(final int position, SwipeMenu menu,
                                                       int index) {
                            switch (index) {
                                case 0:
                                    LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                                    LeMachine lm = MyTeacherApp.getInstance().getBabyTeacher();
                                    sendDeviceDownloadMsg(lu.id, lm.id, mArrayList.get(position),
                                            "start");
                                    break;
                                case 1:
                                    new CustomAsyncTask(StoryDetailActivity.this, new IAsyncTask() {
                                        @Override
                                        public void onRecieveData(Activity activity,
                                                                  ResponseResult result) {
                                            if (result.isSuccess()) {
                                                try {
                                                    JSONObject jsonObject = new JSONObject(result.data);

                                                    int status = 0;
                                                    if (Tools.isNotEmpty(jsonObject)
                                                            && jsonObject.has("status")) {
                                                        status = jsonObject.getInt("status");
                                                    }

                                                    if (status == 1) {
                                                        mArrayList.get(position).favorite = true;
                                                        toastShow("收藏成功");
                                                    } else {
                                                        mArrayList.get(position).favorite = false;
                                                        toastShow("取消收藏");
                                                    }

                                                    storylist.setAdapter(mNumberAdapter);
                                                    initAndUpdateSwipeMenu();
                                                    mNumberAdapter.notifyDataSetChanged();
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }

                                        @Override
                                        public ResponseResult doInbackground(Activity activity) {
                                            HashMap<String, Object> param_ = new HashMap<String, Object>();
                                            param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
                                            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                                            param_.put("category", catalog);
                                            param_.put("foreign_id", mArrayList.get(position).id);
                                            return HttpUtils.startRequest(HttpUtils.HOST_API
                                                            + HttpUtils.ADD_FAVORITE_METHOD_POST, param_,
                                                    HttpUtils.TAG_POST_REQUEST);
                                        }
                                    }).execute();
                                    // if (mArrayList.get(position).favorite) {
                                    // // TODO
                                    // } else {
                                    //
                                    // }
                                    break;
                            }
                            return false;
                        }
                    });

            // set SwipeListener
            storylist.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

                @Override
                public void onSwipeStart(int position) {
                    // swipe start
                }

                @Override
                public void onSwipeEnd(int position) {
                    // swipe end

                    // if (position >= 0) {
                    // mArrayList.get(position).showMore = true;
                    // mNumberAdapter.notifyDataSetChanged();
                    // } else {
                    // mArrayList.get(position).showMore = false;
                    // mNumberAdapter.notifyDataSetChanged();
                    // }

                    // if (storylist.isShowMore()) {
                    // mArrayList.get(position).showMore = ;
                    // }

                    // if (position < 0) {
                    // position = posClick;
                    // }
                    //
                    // if (position >= 0) {
                    // mArrayList.get(position).showMore = storylist.isShowMore();
                    // mNumberAdapter.notifyDataSetChanged();
                    // }

                    // if (position > -1) {
                    // // 展开
                    // lastPOS = position;
                    // mArrayList.get(position).showMore = true;
                    // mNumberAdapter.curPos = position;
                    // mNumberAdapter.notifyDataSetChanged();
                    // } else {
                    // // 收缩
                    // mArrayList.get(lastPOS).showMore = false;
                    // mNumberAdapter.curPos = position;
                    // mNumberAdapter.notifyDataSetChanged();
                    //
                    // }
                }

                @Override
                public void onClickSwipeOpen(int position) {
                    // if (storylist.isShowMore()) {
                    // mArrayList.get(position).showMore = true;
                    // mNumberAdapter.notifyDataSetChanged();
                    // }

                }
            });

            storylist.setOnItemClickListener(this);

            // 定位到列表对应位置
            if (mSort > 0) {
                highlightPos(mSort - 1);
            } else {
                highlightPos(0);
            }
        } else {
            mNumberAdapter.notifyDataSetChanged();

            // 定位到列表对应位置
            if (isLoadMore) {
                storylist.setSelection(mArrayList.size() - 1);
            } else {
                if (mSort > 0) {
                    highlightPos(mSort - 1);
                } else {
                    highlightPos(0);
                }
            }

            if (mArrayList != null && mArrayList.size() == detailVo.getTotal()) {
                storylistPullLayout.refreshFinish(PullToRefreshLayout.LOAD_COMPLETED);
                storylistPullLayout.loadmoreFinish(PullToRefreshLayout.LOAD_COMPLETED);
            } else {
                storylistPullLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                storylistPullLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            }
        }

    }

    int lastPOS = 0;

    private void requestData() {
        showloading("加载中..");
        new CustomAsyncTask(StoryDetailActivity.this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                dismissLoading();
                if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
                    detailVo = JsonSerializer.getInstance().deserialize(result.data,
                            AlbumCollectionItem.class);
                    updateDetail();
                } else if (Tools.isNotNullStr(result.data)) {
                    toastShow(result.data.toString());
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                if (leUser == null) {
                    leUser = Tools.restoreLeUser();
                }

                param_.put(HttpUtils.TAG_SNO_I, leUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                if (mCartoonVo != null) {
                    return HttpUtils.startRequest(HttpUtils.HOST_API
                                    + HttpUtils.GET_CATALOG_ALBUM + "/" + mCartoonVo.id, param_,
                            HttpUtils.TAG_GET_REQUEST);
                } else {
                    return HttpUtils.startRequest(HttpUtils.HOST_API
                                    + HttpUtils.GET_CATALOG_ALBUM + "/" + album_id, param_,
                            HttpUtils.TAG_GET_REQUEST);
                }

            }
        }).execute();
    }

    protected void updateDetail() {
        title.setText(detailVo.getName());
        content = detailVo.getDescription();
        sumhit = detailVo.getPlay_count();
        ctime = detailVo.getCreated_at();
        ageRange = detailVo.getAge_interval();
        coverUrl = detailVo.getCover();
        catalog = detailVo.getCatalog();
        String blurBgUrl = detailVo.getScreenshot();

        if (Tools.isNotEmpty(coverUrl)) {
            Picasso.with(this).load(coverUrl)
                    .placeholder(getResources().getDrawable(R.drawable.default_cover))
                    .error(getResources().getDrawable(R.drawable.default_cover))
                    .transform(new RoundedTransformation(16, 16))
                    .into(img_cover, new Callback() {

                        @Override
                        public void onSuccess() {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onError() {
                            if (mImageLoader == null) {
                                mImageLoader = new ImageLoader(StoryDetailActivity.this);
                            }
                            mImageLoader.DisplayImage(coverUrl, img_cover, false);

                        }
                    });
        }

        if (Tools.isNotEmpty(blurBgUrl)) {

            final Target mTarget = new Target() {
                @SuppressWarnings("deprecation")
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    mCoverBlurLayout
                            .setBackgroundDrawable(new BitmapDrawable(bitmap));
                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {

                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {

                }
            };

            if (Tools.isNotEmpty(blurBgUrl)) {
                Picasso.with(this).load(blurBgUrl).transform(new BlurTransformation(20))
                        .into(mTarget);
            }



            mCoverBlurLayout.setTag(mTarget);
        }

    }

    private void initListener() {
        img_cover.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showDetailsDialog();
            }
        });
    }

    CartoonVo mCartoonVo;
    private int mbanner_id;

    private void initialize() {

        mAdapterList = new ArrayList<>();
        mArrayList = new ArrayList<>();

        leUser = MyTeacherApp.getInstance().getUserTeacher();
        Intent intent = getIntent();
        if (intent.getIntExtra("id", -1) != -1) {
            album_id = intent.getIntExtra("id", -1);
        } else {

            mCartoonVo = (CartoonVo) intent.getSerializableExtra("cartoon");

        }

        mbanner_id = intent.getIntExtra("banner_id", -1);
        mSort = intent.getIntExtra("sort", -1);

        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("com.jdy.haoduoaiteacher.playstatu");
        mFilter.addAction("state.changed.event");
        registerReceiver(mReceiver, mFilter);
    }

    private void showDetailsDialog() {

        Spannable UpdateTimeSpan, AgeSpan, IntroductionSpan;

        UpdateTimeSpan = new SpannableString(getString(R.string.detail_updatetime)
                + String.valueOf(ctime));
        AgeSpan = new SpannableString(getString(R.string.detail_age) + ageRange);
        IntroductionSpan = new SpannableString("故事简介:" + content);
        IntroductionSpan.setSpan(new TextAppearanceSpan(this, R.style.stylea), 0,
                4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        IntroductionSpan.setSpan(new TextAppearanceSpan(this, R.style.styleb), 4,
                IntroductionSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        UpdateTimeSpan.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), 0,
                5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        UpdateTimeSpan.setSpan(new AbsoluteSizeSpan(16, true), 0, 5,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        UpdateTimeSpan.setSpan(new ForegroundColorSpan(Color.rgb(0, 0, 0)), 0, 5,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        AgeSpan.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), 0, 3,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        AgeSpan.setSpan(new AbsoluteSizeSpan(16, true), 0, 3,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        AgeSpan.setSpan(new ForegroundColorSpan(Color.rgb(0, 0, 0)), 0, 3,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        UpdateTimeSpan.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), 0,
                5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        UpdateTimeSpan.setSpan(new AbsoluteSizeSpan(16, true), 0, 5,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        UpdateTimeSpan.setSpan(new ForegroundColorSpan(Color.rgb(0, 0, 0)), 0, 5,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        AgeSpan.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), 0, 3,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        AgeSpan.setSpan(new AbsoluteSizeSpan(16, true), 0, 3,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        AgeSpan.setSpan(new ForegroundColorSpan(Color.rgb(0, 0, 0)), 0, 3,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        CustomDetailDialog.Builder customBuilder = new CustomDetailDialog.Builder(
                StoryDetailActivity.this);
        customBuilder.setTitle("详情").setFitAges(AgeSpan.toString())
                .setPlayTimes("播放次数: " + sumhit + getString(R.string.detail_number))
                .setUpdateTime(UpdateTimeSpan.toString())
                .setStoryAbs(IntroductionSpan.toString())
                .setNegativeButton("", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        if (mCustomDetailDialog != null) {
            mCustomDetailDialog.dismiss();
        }

        mCustomDetailDialog = customBuilder.create();

        if (!isFinishing()) {
            mCustomDetailDialog.show();
        }
    }

    @Override
    public void onResume() {

        if (!LeConfig.isDeviceConnect) {
            if (device_stateview != null) {
                device_stateview.setPlaying(false);
            }
        }

        super.onResume();
        // mCurrentPlayMode = LePreference.getInstance().getInt("playmode", 2);
    }

    @Override
    public void onPause() {
        super.onPause();
        // LePreference.getInstance().save("playmode", mCurrentPlayMode);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.marking_img:
                showMarkingDialog();
                break;
            case R.id.backs:
                finish();
                break;
            case R.id.mydevice_layout:
//                Intent intent = new Intent(this, DevicePropertyActivity.class);
//                startActivity(intent);
                break;
        }
    }

    private void showMarkingDialog() {
        if (mMarkingDialog != null) {
            mMarkingDialog.dismiss();
        }

        CustomMarkingDialog.Builder customBuilder = new CustomMarkingDialog.Builder(
                this);

        customBuilder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("评分", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                // overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                toastShow("感谢你的评分!");
            }
        });

        mMarkingDialog = customBuilder.create();

        if (!isFinishing()) {
            mMarkingDialog.show();
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("com.jdy.haoduoaiteacher.playstatu")) {
                // playid = intent.getIntExtra("id", 0);
                // boolean defaultValue = intent.getBooleanExtra("defaultItem", false);
                // mNotPlayed = intent.getBooleanExtra("notplayed", false);
                // if (!defaultValue)
                // playvideo(playid, "cartoon");
            } else if (action.equals("state.changed.event")) {
                int i = intent.getIntExtra("PlayState", -1);
                PlayState state = PlayState.values()[i];
                if (state.equals(PlayState.Pause) || state.equals(PlayState.Stop)) {
                    // isPlay = false;
                    // playbutton.setBackgroundResource(R.drawable.ico_play);
                } else if (state.equals(PlayState.Playing)) {
                    // isPlay = true;
                    // playbutton.setBackgroundResource(R.drawable.pause_icon);
                }
            }
        }
    };

    private void playvideo(final int sid, final String status) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    DateUtils.showToast(StoryDetailActivity.this, "已推送到设备播放");
//                    if (LeConfig.isDeviceConnect) {
//                        DateUtils.showToast(StoryDetailActivity.this, "已推送到设备播放");
//                    } else {
//                        DateUtils.showToast(StoryDetailActivity.this, "未连接到设备，请检查设备联网情况！");
//                    }

                } else {
                    LeConfig.isDeviceConnect = false;
                    DateUtils.showToast(StoryDetailActivity.this, "设备不在线");
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {

                HashMap<String, Object> param_ = new HashMap<String, Object>();

                // int uid = -1, volume = -1, minutes = -1;
                param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put(HttpUtils.TAG_ACTION_I, "play");
                param_.put(HttpUtils.TAG_OPERATION_I, "cartoon");
                param_.put(HttpUtils.TAG_TYPE_I, "cartoon");
                param_.put("mode", "im");

                if (mbanner_id >= 0) {
                    param_.put("reference", "banner");
                    param_.put("banner_id", mbanner_id);
                } else {
                    param_.put("reference", "push");
                }

                if (sid != -1) {
                    param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
                }

                param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
                        HttpUtils.TAG_GET_REQUEST);

            }
        }).execute();
    }

    public String getCatalog() {
        return catalog;
    }

    public void highlightPos(int pos) {
        if (pos < mArrayList.size()) {
            storylist.setSelection(pos);
            mNumberAdapter.setHighLightPosition(pos);
        } else {
            mLastpage++;
            isrefreshlist = false;
            getEpisode(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // unBind();

//        if (mImHelper != null) {
//            mImHelper.removeDataReceivedListener(this);
//            mImHelper.removeIMParseListener(this);
//        }

        unregisterReceiver(mReceiver);
    }

    // @Override
    // public void onProgressChanged(VerticalSeekBar VerticalSeekBar, int
    // progress,
    // boolean fromUser) {
    //
    // }
    //
    // @Override
    // public void onStartTrackingTouch(VerticalSeekBar VerticalSeekBar) {
    //
    // }
    //
    // @Override
    // public void onStopTrackingTouch(VerticalSeekBar VerticalSeekBar) {
    //
    // }

    public void onStoryListClicked(int id) {
        // playid = id;
        playvideo(id, "cartoon");
    }

    @Override
    public void onRemoteLogin() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (device_stateview != null) {
                    device_stateview.setPlaying(false);
                }
            }
        });

    }

    @Override
    public void onConnectionChanged(boolean connect) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPowerChanged(int power) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(int updatingStatus) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCheckDeviceVersion(String version) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPlayNextFailed() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPlayPrevFailed() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPlayMedia(final PlayState playState, MediaType type,
                            JSONObject data) {

        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (playState.equals(PlayState.Playing)) {
                    device_stateview.setPlaying(true);
                } else {
                    device_stateview.setPlaying(false);
                }
            }
        });

    }

    @Override
    public void onReceivedVoiceMessage(String streamUrl) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onDataReceived(String data) {
        if (Tools.isNotEmpty(data)) {
            try {
                JSONObject jsonData = new JSONObject(data.toString());

                if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("code")
                        && !jsonData.isNull("act")) {
                    if (jsonData.getString("code").contains("device")
                            && jsonData.getString("act").contains("downloadsize")
                            && !jsonData.isNull("data")) {
                        JSONObject jsonData2 = new JSONObject(jsonData.getString("data"));
                        int size = jsonData2.getInt("size");

                        if (size > 9) {
                            toastShow("已达下载数上限，请稍候再试!");
                        } else {
                            toastShow("已加入下载队列");
                        }

                    } else if (Tools.isNotEmpty(jsonData.getString("act"))
                            && jsonData.getString("act").contains(
                            "Device_APP_Connection_Switched")) {
                        // Intent logoutIntent = new Intent(
                        // "com.jdy.haoduoaiteacher.activity.logout");
                        // sendBroadcast(logoutIntent);
                        //
                        // LeConfig.isLogin = false;
                        // LeConfig.isDeviceActivated = false;
                        // LeConfig.isDeviceBinded = false;
                        // LeConfig.isInfoFilled = false;
                        // LeConfig.isDeviceConnect = false;
                        //
                        // CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
                        // getApplicationContext()).setTitle("下线通知")
                        // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
                        // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        //
                        // @Override
                        // public void onClick(DialogInterface dialog, int which) {
                        // dialog.dismiss();
                        // }
                        // });
                        // final CustomOneBtnDialog cd = cdb.create();
                        // cd.getWindow()
                        // .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                        // cd.setOnDismissListener(new OnDismissListener() {
                        //
                        // @Override
                        // public void onDismiss(DialogInterface dialog) {
                        // Intent toActivityIntent = new Intent(StoryDetailActivity.this,
                        // LoginActivity.class);
                        // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                        // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        // startActivity(toActivityIntent);
                        // finish();
                        // }
                        // });
                        // cd.show();
                    }
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onNetWorkDisconn() {
        if (device_stateview != null) {
            device_stateview.setPlaying(false);
        }

    }
}
